package com.ruoyi.web.controller.system;

import cn.afterturn.easypoi.cache.manager.FileLoaderImpl;
import cn.afterturn.easypoi.cache.manager.POICacheManager;
import cn.afterturn.easypoi.word.WordExportUtil;
import com.google.code.appengine.awt.Color;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import com.ruoyi.system.domain.Invest;
import com.ruoyi.system.domain.Projects;
import com.ruoyi.system.service.ProjectsService;
import com.ruoyi.system.service.ScreenService;
import com.ruoyi.system.util.PoiUtil;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import fr.opensagres.xdocreport.itext.extension.font.IFontProvider;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/system/easyPoi")
@Controller
@CrossOrigin
public class EasyPoiController {
    @Autowired
    private ProjectsService projectsService;
    @Autowired
    private ScreenService screenService;

    /**
     * 简单导出没有图片和Excel
     */
    @GetMapping("/test1")
    public void SimpleWordExport(HttpServletResponse response, Projects projects,@RequestHeader("userId")String userId) {
//        重置响应对象
        response.reset();
        projects.setUserId(userId);
//         指定下载的文件名--设置响应头
        response.setHeader("Content-Disposition", "attachment;filename=test.docx");
        response.setContentType("application/octet-stream");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.addHeader("Access-Control-Allow-Headers", "Content-Disposition");
        // 重要代码解决模板路径问题和缓存
        POICacheManager.setFileLoader(new FileLoaderImpl());
        HashMap<String, Object> query = projectsService.query(projects);
        try {
            XWPFDocument doc = WordExportUtil.exportWord07("poi.docx", query);

            //获取word中所有图表对象
            List<XWPFChart> charts = doc.getCharts();

            //获取第一个单系列柱状图
            XWPFChart singleBarChar = charts.get(0);
            //系列信息
            String[] singleBarSeriesNames = {"计划投资", "实际投资"};
            //分类信息
            String[] singleBarCats = {"01月", "02月", "03月", "04月", "05月", "06月", "07月", "08月", "09月", "10月", "11月", "12月"};
            //值信息
            List<Number[]> singleBarValues = new ArrayList<>();
            Invest invest = new Invest();
            invest.setMouYear(projects.getMouYear());
            invest.setUserId(userId);
            List<Invest> list = screenService.selectInvest(invest);
            Number[] long1 = new Number[12];
            Number[] long2 = new Number[12];
            for (int i = 0; i < list.size(); i++) {
                long1[i] = list.get(i).getMouPlanInvest();
                long2[i] = list.get(i).getMouRealInvest();
            }
            singleBarValues.add(long1);
            singleBarValues.add(long2);
            PoiUtil.wordExportChar(singleBarChar, "梧州市" + projects.getMouYear() + "年项目投资情况统计图 (万元)", singleBarSeriesNames, singleBarCats, singleBarValues);

            doc.write(response.getOutputStream());
            doc.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将word文档， 转换成pdf, 中间替换掉变量
     *
     * @param source  源为word文档， 必须为docx文档
     * @param target  目标输出
     * @param options PdfOptions.create().fontEncoding( "windows-1250" ) 或者其他
     * @throws Exception
     */
    @GetMapping("/test2")
    public void wordConverterToPdf(InputStream source, OutputStream target, PdfOptions options, Projects projects,@RequestHeader("userId")String userId) throws Exception {
        projects.setUserId(userId);
        XWPFDocument doc = new XWPFDocument(new FileInputStream(new File("/opt/server/wzzhgd/ruoyi-admin/src/main/resources/poi2.docx")));
        HashMap<String, Object> params = projectsService.query(projects);
        Map map = new HashMap();
        map.put("plan1", params.get("plan1") + "");
        map.put("plan2", params.get("plan2") + "");
        map.put("sum", params.get("sum") + "");
        map.put("year", params.get("year") + "");
        map.put("sum0", params.get("sum0") + "");
        map.put("Invest0", params.get("Invest0") + "");
        map.put("InvestGoal0", params.get("InvestGoal0") + "");
        map.put("sum3", params.get("sum3") + "");
        map.put("Invest3", params.get("Invest3") + "");
        map.put("InvestGoal3", params.get("InvestGoal3") + "");
        map.put("sum1", params.get("sum1") + "");
        map.put("Invest1", params.get("Invest1") + "");
        map.put("InvestGoal1", params.get("InvestGoal1") + "");
        map.put("sum2", params.get("sum2") + "");
        map.put("Invest2", params.get("Invest2") + "");
        map.put("InvestGoal2", params.get("InvestGoal2") + "");
        map.put("UnderMillion", params.get("UnderMillion") + "");
        map.put("Million", params.get("Million") + "");
        map.put("TenMillion", params.get("TenMillion") + "");
        map.put("Billion", params.get("Billion") + "");
        map.put("Num1", params.get("Num1") + "");
        map.put("Num2", params.get("Num2") + "");
        map.put("Num3", params.get("Num3") + "");
        map.put("Num4", params.get("Num4") + "");
        paragraphReplace(doc.getParagraphs(), map);
        // 中文字体处理
        options.fontProvider(new IFontProvider() {
            public Font getFont(String familyName, String encoding, float size, int style, Color color) {
                color = Color.black;
                familyName = "测试";
                try {
                    BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                    Font fontChinese = new Font(bfChinese, size, style, color);
                    if (familyName != null)
                        fontChinese.setFamily(familyName);
                    return fontChinese;
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            }

        });
        PdfConverter.getInstance().convert(doc, target, options);
    }

    /**
     * 替换段落中内容
     */
    private static void paragraphReplace(List<XWPFParagraph> paragraphs, Map<String, String> params) {
        if (params != null && !params.isEmpty()) {
            for (XWPFParagraph p : paragraphs) {
                for (XWPFRun r : p.getRuns()) {
                    String content = r.getText(r.getTextPosition());
                    if (StringUtils.isNotEmpty(content)) {
                        if (content.indexOf("a") != -1) {
                            String s = content.replace("a", params.get("year"));
                            r.setText(s, 0);
                        }
                        if (content.indexOf("b") != -1) {
                            String s = content.replace("b", params.get("sum"));
                            r.setText(s, 0);
                        }
                        if (content.indexOf("c") != -1) {
                            String s = content.replace("c", params.get("sum0"));
                            r.setText(s, 0);
                        }
                        if (content.indexOf("d") != -1) {
                            String s = content.replace("d", params.get("Invest0"));
                            r.setText(s, 0);
                        }
                        if (content.indexOf("e") != -1) {
                            String s = content.replace("e", params.get("InvestGoal0"));
                            r.setText(s, 0);
                        }
                        if (content.indexOf("f") != -1) {
                            String s = content.replace("f", params.get("sum3"));
                            r.setText(s, 0);
                        }
                        if (content.indexOf("g") != -1) {
                            String s = content.replace("g", params.get("Invest3"));
                            r.setText(s, 0);
                        }
                        if (content.indexOf("h") != -1) {
                            String s = content.replace("h", params.get("InvestGoal3"));
                            r.setText(s, 0);
                        }
                        if (content.indexOf("i") != -1) {
                            String s = content.replace("i", params.get("sum1"));
                            r.setText(s, 0);
                        }
                        if (content.indexOf("j") != -1) {
                            String s = content.replace("j", params.get("Invest1"));
                            r.setText(s, 0);
                        }
                        if (content.indexOf("k") != -1) {
                            String s = content.replace("k", params.get("InvestGoal1"));
                            r.setText(s, 0);
                        }
                        if (content.indexOf("l") != -1) {
                            String s = content.replace("l", params.get("sum2"));
                            r.setText(s, 0);
                        }
                        if (content.indexOf("m") != -1) {
                            String s = content.replace("m", params.get("Invest2"));
                            r.setText(s, 0);
                        }
                        if (content.indexOf("n") != -1) {
                            String s = content.replace("n", params.get("InvestGoal2"));
                            r.setText(s, 0);
                        }
                        if (content.indexOf("o") != -1) {
                            String s = content.replace("o", params.get("plan1"));
                            r.setText(s, 0);
                        }
                        if (content.indexOf("p") != -1) {
                            String s = content.replace("p", params.get("plan2"));
                            r.setText(s, 0);
                        }
                        if (content.indexOf("q") != -1) {
                            String s = content.replace("q", params.get("UnderMillion"));
                            r.setText(s, 0);
                        }
                        if (content.indexOf("r") != -1) {
                            String s = content.replace("r", params.get("Million"));
                            r.setText(s, 0);
                        }
                        if (content.indexOf("s") != -1) {
                            String s = content.replace("s", params.get("TenMillion"));
                            r.setText(s, 0);
                        }
                        if (content.indexOf("t") != -1) {
                            String s = content.replace("t", params.get("Billion"));
                            r.setText(s, 0);
                        }
                        if (content.indexOf("u") != -1) {
                            String s = content.replace("u", params.get("Num1"));
                            r.setText(s, 0);
                        }
                        if (content.indexOf("v") != -1) {
                            String s = content.replace("v", params.get("Num2"));
                            r.setText(s, 0);
                        }
                        if (content.indexOf("w") != -1) {
                            String s = content.replace("w", params.get("Num3"));
                            r.setText(s, 0);
                        }
                        if (content.indexOf("x") != -1) {
                            String s = content.replace("x", params.get("Num4"));
                            r.setText(s, 0);
                        }
                    }
                }
            }
        }
    }
}
